'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Users, ShoppingCart, Package, MessageSquare, Calendar, ArrowUpDown } from 'lucide-react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line, Pie } from 'react-chartjs-2';

// 注册Chart.js组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend
);

// 格式化日期函数
function formatDate(dateString) {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 订单状态映射
const orderStateMap = {
  0: '待接单',
  1: '已接单',
  2: '已完成',
  3: '已取消'
};

// 生成随机颜色
function generateRandomColors(count) {
  const colors = [];
  for (let i = 0; i < count; i++) {
    const r = Math.floor(Math.random() * 200);
    const g = Math.floor(Math.random() * 200);
    const b = Math.floor(Math.random() * 200);
    colors.push(`rgba(${r}, ${g}, ${b}, 0.6)`);
  }
  return colors;
}

export default function DashboardPage() {
  const [stats, setStats] = useState({
    users: 0,
    commodities: 0,
    orders: 0,
    feedbacks: 0
  });
  const [recentOrders, setRecentOrders] = useState([]);
  const [categories, setCategories] = useState([]);
  const [monthlySales, setMonthlySales] = useState([]);
  const [popularCommodities, setPopularCommodities] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取用户总数
        const usersResponse = await fetch('/api/users');
        const usersData = await usersResponse.json();
        
        // 获取商品总数
        const commoditiesResponse = await fetch('/api/commodities');
        const commoditiesData = await commoditiesResponse.json();
        
        // 获取订单总数
        const ordersResponse = await fetch('/api/orders');
        const ordersData = await ordersResponse.json();
        
        // 获取反馈总数
        const feedbacksResponse = await fetch('/api/feedbacks');
        const feedbacksData = await feedbacksResponse.json();
        
        // 获取分类数据
        const categoriesResponse = await fetch('/api/categories');
        const categoriesData = await categoriesResponse.json();
        
        // 获取热门商品数据a
        const popularCommoditiesResponse = await fetch('/api/commodities/popular');
        const popularCommoditiesData = await popularCommoditiesResponse.json();
        
        // 更新统计数据
        setStats({
          users: usersData.users.length,
          commodities: commoditiesData.commodities.length,
          orders: ordersData.orders.length,
          feedbacks: feedbacksData.feedbacks.length
        });

        // 更新最近订单数据（取最近10条）
        const sortedOrders = [...ordersData.orders].sort((a, b) => 
          new Date(b.orderTime) - new Date(a.orderTime)
        ).slice(0, 10);
        setRecentOrders(sortedOrders);

        // 更新分类数据
        setCategories(categoriesData.categories);

        // 更新热门商品数据
        setPopularCommodities(popularCommoditiesData.popularCommodities || []);

        // 生成月度销售数据（模拟数据）
        const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
        const salesData = months.map(() => Math.floor(Math.random() * 100) + 20);
        setMonthlySales({ months, salesData });
      } catch (error) {
        console.error('获取统计数据失败:', error);
      }
    };

    fetchData();
  }, []);

  // 销售趋势图配置
  const salesChartData = {
    labels: monthlySales.months || [],
    datasets: [
      {
        label: '销售额',
        data: monthlySales.salesData || [],
        borderColor: 'rgb(53, 162, 235)',
        backgroundColor: 'rgba(53, 162, 235, 0.5)',
      },
    ],
  };

  const salesChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: '月度销售趋势',
      },
    },
  };

  // 分类分布图配置
  const categoryChartData = {
    labels: categories.map(cat => cat.categoryName),
    datasets: [
      {
        label: '商品数量',
        data: categories.map(cat => cat.commodityCount),
        backgroundColor: generateRandomColors(categories.length),
        borderWidth: 1,
      },
    ],
  };

  const categoryChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'right',
      },
      title: {
        display: true,
        text: '商品分类分布',
      },
    },
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">仪表盘</h1>
        <p className="text-muted-foreground">系统概览和关键指标</p>
      </div>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">概览</TabsTrigger>
          <TabsTrigger value="analytics">分析</TabsTrigger>
        </TabsList>
        <TabsContent value="overview" className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">用户总数</CardTitle>
                <Users className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.users}</div>
                <p className="text-xs text-muted-foreground">平台注册用户总数</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">商品总数</CardTitle>
                <ShoppingCart className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.commodities}</div>
                <p className="text-xs text-muted-foreground">平台发布商品总数</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">订单总数</CardTitle>
                <Package className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.orders}</div>
                <p className="text-xs text-muted-foreground">平台交易订单总数</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">反馈总数</CardTitle>
                <MessageSquare className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.feedbacks}</div>
                <p className="text-xs text-muted-foreground">用户提交反馈总数</p>
              </CardContent>
            </Card>
          </div>

          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
            <Card className="col-span-4">
              <CardHeader>
                <CardTitle>最近交易</CardTitle>
                <CardDescription>最近的10笔交易记录</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {recentOrders.length > 0 ? (
                    <div className="rounded-md border">
                      <div className="grid grid-cols-5 bg-muted/50 p-2 text-xs font-medium">
                        <div>交易时间</div>
                        <div>商品名称</div>
                        <div>价格</div>
                        <div>买家</div>
                        <div>状态</div>
                      </div>
                      {recentOrders.map((order) => (
                        <div key={order.orderId} className="grid grid-cols-5 border-t p-2 text-sm">
                          <div className="flex items-center">
                            <Calendar className="mr-1 h-3 w-3" />
                            {formatDate(order.orderTime)}
                          </div>
                          <div className="truncate">{order.goodsName}</div>
                          <div>¥{order.goodsPrice.toFixed(2)}</div>
                          <div>{order.customerName}</div>
                          <div>
                            <span className={`inline-flex items-center rounded-full px-2 py-1 text-xs ${order.orderState === 2 ? 'bg-green-100 text-green-700' : order.orderState === 3 ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700'}`}>
                              {orderStateMap[order.orderState] || '未知状态'}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="flex h-[200px] items-center justify-center border rounded">
                      <p className="text-muted-foreground">暂无交易数据</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
            <Card className="col-span-3">
              <CardHeader>
                <CardTitle>热门商品</CardTitle>
                <CardDescription>订单量最高的商品</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {popularCommodities.length > 0 ? (
                    popularCommodities.map((commodity, index) => (
                      <div key={commodity.goodsId} className="flex items-center">
                        <div className="font-medium">{index + 1}. {commodity.goodsName}</div>
                        <div className="ml-auto text-sm text-muted-foreground">¥{commodity.goodsPrice.toFixed(2)} · {commodity._count.orders || 0} 订单</div>
                      </div>
                    ))
                  ) : (
                    <div className="flex h-[200px] items-center justify-center border rounded">
                      <p className="text-muted-foreground">暂无热门商品数据</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
        <TabsContent value="analytics" className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-2">
            <Card className="col-span-1">
              <CardHeader>
                <CardTitle>销售趋势</CardTitle>
                <CardDescription>过去6个月的销售趋势</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  {monthlySales.months && monthlySales.months.length > 0 ? (
                    <Line options={salesChartOptions} data={salesChartData} />
                  ) : (
                    <div className="flex h-full items-center justify-center border rounded">
                      <p className="text-muted-foreground">加载销售趋势数据中...</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
            <Card className="col-span-1">
              <CardHeader>
                <CardTitle>商品分类分布</CardTitle>
                <CardDescription>各分类商品数量占比</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  {categories.length > 0 ? (
                    <Pie options={categoryChartOptions} data={categoryChartData} />
                  ) : (
                    <div className="flex h-full items-center justify-center border rounded">
                      <p className="text-muted-foreground">加载分类数据中...</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}